#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

namespace dict_ns
{
    const std::string defaultpath = "./Dict.txt";
    const std::string sep = ": ";

    class Dict
    {
    private:
        bool Load()
        {
            // 1. 打开文件
            std::ifstream in(_dict_conf_filepath);
            if (!in.is_open())
            {
                LOG(RATAL, "open %s error\n", _dict_conf_filepath);
                return false;
            }
            // 读文件
            std::string line;
            while (std::getline(in, line))
            {
                // 查找字典
                if (line.empty()) continue;
                auto pos = line.find(sep);
                if (pos == std::string::npos) continue;
                std::string word = line.substr(0, pos);
                if (word.empty()) continue;
                std::string han = line.substr(pos + sep.size());
                if (han.empty()) continue;
                LOG(DEBUG, "Load info:[%s:%s]\n", word.c_str(), han.c_str());

                //插入数据
                _dict.insert(std::make_pair(word, han));
            }
            // 关闭文件
            in.close();

            LOG(RATAL, "Load %s success....\n", _dict_conf_filepath);
            return true;
        }
    public:
        Dict(const std::string &path = defaultpath):_dict_conf_filepath(path)
        {
            Load();
        }

        std::string Translate(const std::string &word, bool &ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if (iter == _dict.end())
            {
                false;
                return "未找到";
            }
            return _dict[word];
        }
        ~Dict()
        {}
    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_conf_filepath;
    };
}